<template>
  <Page class="bg-[#f5f5f5] min-h-screen">
    <PageHeader title="课程详情" class="!bg-red" />
    <!-- <view class="h-[120rpx]"></view> -->
    <view class="w-full rounded-2xl imgss mt-[-32rpx] mb-[24rpx] mx-auto bg-[#e6eaf2] flex items-center justify-center relative">
      <image :src="getFullPath(courseDetail?.cover)" class="w-full h-auto h-min-[400rpx] object-cover block" :style="{ minHeight: '100%' }" />
      <image :src="playBtn" class="w-[100rpx] h-[100rpx] rounded-full absolute top-0 right-0 left-0 bottom-0 m-auto cursor-pointer" @click="openVideoPlayer"></image>
    </view>
    <!-- 课程信息卡片 -->
    <view class="bg-white rounded-2xl shadow-md p-[32rpx] mx-[24rpx] mb-[24rpx] relative z-10">
      <view class="text-[36rpx] font-bold mb-[16rpx] text-[#222]">{{ courseDetail.title }}</view>
      <view class="flex gap-x-8 mb-[16rpx]">
        <view class="text-[#666] text-[26rpx]">{{ courseDetail.member_number }}人学习</view>
        <view class="text-[#666] text-[26rpx]">时长：{{ formatDuration(courseDetail.cycle || 0) }}</view>
        <!-- <view class="text-[#666] text-[26rpx]">{{ course.rating }}分</view> -->
      </view>
      <view class="text-[#FF4D4F] text-[36rpx] font-bold mb-[16rpx]">¥{{ courseDetail.price }}</view>
      <!-- <view class="flex items-center mb-[8rpx]">
        <image :src="getFullPath(courseDetail?.teachers_pic ?? '')" class="w-[40rpx] h-[40rpx] rounded-full mr-[12rpx] object-cover bg-[#e6eaf2]" @error="onAvatarError" />
        <view class="text-[28rpx] text-[#333]">{{ courseDetail.teacher_name }}</view>
      </view> -->
    </view>
    <!-- 简介区块 -->
    <view class="text-[30rpx] font-bold px-[32rpx] py-[20rpx] bg-[#f9f9f9] mt-[8rpx] text-[#0033ff]">课程简介</view>
    <view class="bg-white px-[32rpx] py-[24rpx] text-[28rpx] leading-[1.7] text-[#333]">{{ courseDetail.introduction || '暂无' }}</view>
    <!-- 目录区块 -->
    <view class="text-[30rpx] font-bold px-[32rpx] py-[20rpx] bg-[#f9f9f9] mt-[8rpx] text-[#0033ff]">课程目录</view>
    <view class="bg-white mb-[120rpx]">
      <view v-for="(chapter, idx) in lessons" :key="chapter.id" class="px-[32rpx] py-[24rpx] border-b border-[#eee]">
        <view class="flex-1 text-[28rpx] font-bold">{{ chapter.title }} </view>
        <view class="flex items-center justify-between text-[#666]">
          <view class="text-[24rpx] mt-[2rpx] mr-2">课时: {{ formatDuration(chapter.duration) }}</view>
          <view class="text-[24rpx] mt-[2rpx] mr-2">上课时间: {{ chapter.date_time }}</view>
          <view v-if="courseDetail.byStatus == 1" class="flex items-center justify-end my-2">
            <template v-if="courseDetail.online != 0">
              <nut-button size="small" type="warning" @click="playVideo(chapter)">播放</nut-button>
            </template>
            <template v-else>
              <nut-button size="small" type="success" @click="signIn(chapter)" v-if="!hasSign(chapter)">去签到</nut-button>
              <nut-button size="small" type="success" disabled v-else>已签到</nut-button>
            </template>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部吸顶购买栏 -->
    <view
      class="fixed bottom-0 left-0 right-0 w-full max-w-[750rpx] mx-auto box-border bg-white px-[32rpx] py-[20rpx] shadow-[0_-2rpx_8rpx_rgba(0,0,0,0.06)] flex items-center justify-between z-[999] border-t border-[#eee]"
    >
      <view class="flex-1">
        <!-- <span class="text-[26rpx] text-[#999] line-through mr-[12rpx]">¥{{ course.originalPrice }}</span> -->
        <span class="text-[#FF4D4F] text-[36rpx] font-bold">¥{{ courseDetail.price }}</span>
      </view>

      <!-- 已购买且已支付状态 -->
      <view v-if="courseDetail.byStatus !== 0 && courseDetail.pay_status === 1" class="flex gap-[16rpx]">
        <text class="text-[28rpx] px-[32rpx] border-[#165DFF] text-[#999] font-medium">已购买</text>
        <!-- <nut-button type="default" size="normal" class="rounded-2xl text-[28rpx] px-[32rpx] border-[#165DFF] text-[#165DFF] font-medium" @click="handleRefund"> 申请退款 </nut-button> -->
      </view>

      <!-- 未购买状态 -->
      <view v-if="courseDetail.byStatus === 0" class="flex gap-[16rpx]">
        <nut-button type="primary" class="rounded-2xl text-[28rpx] px-[32rpx] bg-[#165DFF] font-medium" @click="purchaseCourse"> 立即购买 </nut-button>
      </view>

      <!-- 已购买但未支付状态 -->
      <view v-if="courseDetail.byStatus !== 0 && courseDetail.pay_status === 0" class="flex gap-[16rpx]">
        <nut-button type="default" size="normal" class="rounded-2xl text-[28rpx] px-[32rpx] border-[#FF4D4F] text-[#FF4D4F] font-medium" @click="cancelTheOrder"> 取消订单 </nut-button>
        <nut-button type="primary" class="rounded-2xl text-[28rpx] px-[32rpx] bg-[#165DFF] font-medium" @click="handlePayment"> 支付订单 </nut-button>
      </view>
    </view>
  </Page>

  <!-- 全屏视频播放器 -->
  <view v-if="showVideoPlayer" class="video-player-overlay fixed inset-0 bg-black z-[66666] flex items-center justify-center">
    <view class="video-player-container w-full h-full relative">
      <!-- 关闭按钮 -->
      <view class="close-btn absolute top-[20rpx] right-[20rpx] z-10 w-[80rpx] h-[80rpx] rounded-full flex items-center justify-center" @click="closeVideoPlayer">
        <image :src="closeBtn" class="w-[80rpx] h-[80rpx]"></image>
      </view>
      
      <!-- 视频播放器 -->
      <video 
        v-if="courseDetail.video_url"
        :src="getFullPath(courseDetail.video_url)" 
        class="w-full h-full"
        controls
        autoplay
        object-fit="contain"
      />
    </view>
  </view>

  <!-- 支付方式选择弹窗 -->
  <PaymentMethodModal 
    v-model="showPaymentModal" 
    :amount="courseDetail.price || 0"
    @confirm="handlePaymentConfirm"
    @cancel="handlePaymentCancel"
  />
</template>

<script setup lang="ts">
import Taro from "@tarojs/taro";
import { ref } from "vue";
import PageHeader from "@/components/PageHeader.vue";
import PaymentMethodModal from "@/components/PaymentMethodModal.vue";
import { getCurrentInstance } from "@tarojs/runtime";
import { getFullPath, post } from "@/utils/request";
import { useUserStore } from "@/store/user";
// import playBtn from '@/assets/pic/play.png'
// const playBtn = 'http://www.dzgktf.com/templets/default/images/play.png'
import playBtn from '@/assets/pic/play.png'
import closeBtn from '@/assets/pic/close.png'

// 默认图片路径
const defaultBookImage = "http://www.dzgktf.com/templets/default/images/wtyt.jpg";
const defaultAvatarImage = "http://www.dzgktf.com/templets/default/images/avatar.jpg";

const formatDuration = (minutes: number | string | undefined) => {
  if (!minutes || parseInt(minutes as string) <= 0) {
    return '暂无';
  }
  
  const totalMinutes = Math.round(parseInt(minutes as string));
  const hours = Math.floor(totalMinutes / 60);
  const remainingMinutes = totalMinutes % 60;
  
  if (hours === 0) {
    return `${remainingMinutes}分钟`;
  } else if (remainingMinutes === 0) {
    return `${hours}小时`;
  } else {
    return `${hours}小时${remainingMinutes}分钟`;
  }
};

/**
 * 课程详情页面
 * @description 课程信息、简介、目录、底部购买栏，严格按设计稿和Cursor规则实现。
 * @performance 只渲染必要内容，mock数据，移动端适配。
 */
//获取主课程信息的数据格式
interface CourseColumn {
  member_id: null;
  teachers_pic: null;
  sign_rate: null;
  teacher_name: null;
  member_number: null;
  teachers_introduction: null;
  create_time: number;
  pay_number: null;
  title: null;
  type: null;
  cycle_type: null;
  cycle: null;
  cover: null;
  update_time: null | number;
  pay_status: null;
  total_amount: null;
  price: null;
  progress: null;
  id: number;
  introduction: null;
  status: number;
  byStatus: null;
}
//获取相关章节的数据格式
interface LessonsColumn {
  duration: number;
  update_time: number;
  date_time: string;
  create_time: number;
  id: number;
  status: number;
  title: string;
  videoUrl: string;
  trainingId: number;
}

interface CourseItem {
  columns: CourseColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface LessonsItem {
  columns: LessonsColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}
//定义详情页展示信息
const courseDetail = ref({
  member_id: null,
  teachers_pic: null,
  sign_rate: null,
  teacher_name: null,
  member_number: null,
  teachers_introduction: null,
  create_time: null,
  pay_number: null,
  title: null,
  type: null,
  cycle_type: null,
  cycle: null,
  cover: null,
  update_time: null,
  pay_status: null,
  total_amount: null,
  price: null,
  progress: null,
  id: null,
  introduction: null,
  status: null,
  byStatus: null,
  payId: null,
  online: null,
  video_url: null,
});
//接收主课程数据
const courseDetailData = ref();
//接收章节数据
const lessons = ref<any[]>([]);
const goBack = () => {
  Taro.navigateBack();
};

const hasOrderId = ref(false); // 是否有订单号 //购买状态
// 控制全屏视频播放器显示隐藏
const showVideoPlayer = ref(false);

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);
const userStore = useUserStore();

const playVideo = (chapter: any) => {
  Taro.navigateTo({
    url: `/pages/course/video-player?id=${courseDetail.value.id}&chapter=${chapter.id}`,
  });
};

const hasSign = (chapter: any) => {
  const suc = checkIds.value.find((i) => i == chapter.id);
  return suc;
};

const signIn = (chapter: any) => {
  Taro.showModal({
    title: "签到",
    content: "确定要签到吗？",
    success: (result: any) => {
      if (result) {
        console.log("chapter", chapter);
        const suc = checkIds.value.find((i) => i == chapter.id);
        if (suc) {
          Taro.showToast({ title: "已签到", icon: "error", duration: 2000 });
          return;
        }
        console.log("chapter.training_id", checkIds.value);
        const ary = [...checkIds.value, chapter.id];
        post("/training/updateCheckIds", {
          id: courseDetail.value.payId,
          checkIds: ary.join(","),
        }).then((res) => {
          console.log("res", res);
          if (res.code == 0) {
            Taro.showToast({ title: "签到成功", icon: "success", duration: 2000 });
            checkIds.value = ary;
          } else {
            Taro.showToast({ title: "签到失败", icon: "error", duration: 2000 });
          }
          checkIds.value = res.data.split(",") || [];
        });
      }
    },
  });
  // Taro.navigateTo({
  //   url: `/pages/webs/training?id=${chapter.training_id}`,
  // });
  // if(checkIds.value.includes(chapter.id)){
  //   checkIds.value.push(chapter.id)
  // }
};

const course = ref({
  cover: "https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg", // 可访问的课程封面图片
  title: "HTML5与CSS3基础教程",
  students: 128,
  lessons: 20,
  rating: 4.9,
  price: 99,
  originalPrice: 199,
  teacher: {
    name: "张老师",
    avatar: "https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg", // 可访问的讲师头像
  },
  description: "本课程从零开始讲解HTML5和CSS3的基础知识，包括HTML5新标签、语义化结构、CSS3选择器、盒模型、Flex布局、响应式设计等核心内容。通过大量实例演示，帮助学员快速掌握现代网页开发基础技术。",
});

const checkIds = ref<any[]>([]);

/**获取主课程ID的课程详情信息*/
getCourseInformation();
function getCourseInformation() {
  const courseId = getCurrentInstance();
  const id = (courseId.router?.params.id as string) || "";
  const submitData = {
    trainingId: id,
  };
  post("/training/getById", submitData).then((res) => {
    // 直接处理res.data.columns（单条数据对象），无需map遍历
    courseDetailData.value = {
      member_id: res.data.columns.member_id,
      teachers_pic: res.data.columns.teachers_pic,
      sign_rate: res.data.columns.sign_rate,
      teacher_name: res.data.columns.teacher_name,
      member_number: res.data.columns.member_number,
      teachers_introduction: res.data.columns.teachers_introduction,
      create_time: res.data.columns.create_time,
      pay_number: res.data.columns.pay_number, // 注意：接口返回中没有该字段，可能为undefined
      title: res.data.columns.title,
      type: res.data.columns.type,
      cycle_type: res.data.columns.cycle_type,
      cycle: res.data.columns.cycle,
      cover: res.data.columns.cover,
      update_time: res.data.columns.update_time,
      pay_status: res.data.columns.pay_status, // 接口返回中没有该字段，可能为undefined
      total_amount: res.data.columns.total_amount, // 接口返回中没有该字段，可能为undefined
      price: res.data.columns.price,
      progress: res.data.columns.progress,
      id: res.data.columns.id,
      introduction: res.data.columns.introduction,
      status: res.data.columns.status, // 接口返回中没有该字段，可能为undefined
      byStatus: res.data.columns.byStatus,
      payId: res.data.columns.payId,
      online: res.data.columns.online,
      video_url: res.data.columns.video_url,
    };
    checkIds.value = res.data.columns?.check_ids?.split(",") || [];
    courseDetail.value = courseDetailData.value;
    console.log("courseDetail", courseDetail.value);
    //查询成功则继续查询章节信息
    if (res.code === 0) {
      const submitId = {
        trainingId: courseDetail.value.id,
      };
      post("/training/list", submitId).then((res) => {
        lessons.value = res.data.map((item: LessonsItem) => ({
          duration: item.columns.duration,
          update_time: item.columns.update_time,
          date_time: item.columns.date_time,
          create_time: item.columns.create_time,
          id: item.columns.id,
          status: item.columns.status,
          title: item.columns.title,
          videoUrl: item.columns.videoUrl,
          trainingId: item.columns.trainingId,
        }));
        /*if(res.code===0){
          Taro.showToast({ title: '查询成功', icon: 'success',duration: 2000 })
        }
        else{
          Taro.showToast({ title: '查询失败', icon: 'success',duration: 2000 })
        }*/
      });
    }
  });
}

const detailCourse = (item: any) => {
  Taro.navigateTo({
    // url: `/pages/webs/training?id=${item.id}&payId=${item.payId}`,
    url: `/pages/course/detail?id=${item.id}&payId=${item.payId}`,
  });
};

function purchaseCourse() {
  post("/training/buy", { trainingId: courseDetail.value.id }).then((res) => {
    if (res.code === 0) {
      // 保存订单号
      courseDetail.value.payId = res.data;
      hasOrderId.value = true;
      // 生成订单后直接显示支付弹窗
      showPaymentModal.value = true;
    } else if (res.code === -1) {
      Taro.showToast({ title: "不能重复购买", icon: "error", duration: 2000 });
    } else {
      Taro.showToast({ title: "生成订单失败", icon: "error", duration: 2000 });
    }
  });
}

// 申请退款
const handleRefund = () => {
  Taro.showToast({
    title: "已申请退款",
    icon: "success",
  });
};

// 支付订单 - 显示支付方式选择弹窗
const handlePayment = () => {
  if (!courseDetail.value.payId) {
    Taro.showToast({ title: "请先生成订单", icon: "error", duration: 2000 });
    return;
  }
  // 显示支付方式选择弹窗
  showPaymentModal.value = true;
};

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  if (!courseDetail.value.payId) {
    Taro.showToast({ title: "订单信息不存在", icon: "error", duration: 2000 });
    return;
  }

  try {
    // 调用支付接口
    const submit = {
      bid: courseDetail.value.payId,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    };
    const payRes = await post("/pay/training", submit);

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        if (typeof (window as any).WeixinJSBridge !== "undefined") {
          (window as any).WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            {
              appId: payRes.data.appid,
              timeStamp: payRes.data.timeStamp,
              nonceStr: payRes.data.nonceStr,
              package: payRes.data.prepayId,
              signType: "RSA",
              paySign: payRes.data.paySign,
            },
            function (res: any) {
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                Taro.showToast({ title: "购买成功", icon: "success", duration: 2000 });
                setTimeout(() => {
                  Taro.navigateBack();
                }, 1500);
              } else {
                Taro.showToast({ title: "购买失败", icon: "error", duration: 2000 });
              }
            }
          );
        }
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - parseFloat(courseDetail.value.price || '0');
          userStore.updateBalance(newBalance);
          
          setTimeout(() => {
            Taro.navigateBack();
          }, 2000);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || payRes.data.message || "支付失败",
            icon: "error",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: "支付失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error('支付失败:', error);
    Taro.showToast({
      title: "支付失败，请重试",
      icon: "none",
      duration: 2000,
    });
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  showPaymentModal.value = false;
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
    duration: 2000,
  });
};

// 取消订单
const cancelTheOrder = () => {
  post("/training/update", { id: Number(courseDetail.value.payId), status: 6 }).then((res) => {
    if (res.code == 0) {
      Taro.showToast({
        title: "取消成功！",
        icon: "success",
        duration: 2000,
      });
      setTimeout(() => {
        Taro.redirectTo({ url: "/pages/course/index" });
      }, 2000);
    }
  });
};

function onAvatarError(e: any) {
  e.target.src = defaultAvatarImage;
}

function onBookError(e: any) {
  e.target.src = defaultBookImage;
}

// 打开视频播放器
const openVideoPlayer = () => {
  if (!courseDetail.value.video_url) {
    Taro.showToast({ title: '暂无视频', icon: 'none', duration: 2000 });
    return;
  }
  showVideoPlayer.value = true;
};

// 关闭视频播放器
const closeVideoPlayer = () => {
  showVideoPlayer.value = false;
};
</script>

<style scoped lang="scss">
.imgss{
  min-height: 400rpx !important;
}
</style>
